package com.sams.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
 
import com.sams.entity.User;
import com.sams.entity.UserExample;
import com.sams.entity.UserExample.Criteria;
import com.sams.mapper.UserMapper;
import com.sams.service.UserService;
import com.sams.util.SamResult;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;
	
	public SamResult login(String username, String password) {
	   //根据用户名  密码查询  
	     UserExample example = new UserExample();
	     Criteria criteria = example.createCriteria();
	     //通过调用方法 封装查询条件
	     criteria.andUsercodeEqualTo(username.trim());
	     criteria.andPasswordEqualTo(password.trim());
	     
		List<User> list = userMapper.selectByExample(example);
		if(list!=null && list.size()>0) {
			User user =  list.get(0);
			//登陸成功
			SamResult result = new  SamResult(200, "登陆成功", user);
			return result;
		}else {
			SamResult result = new  SamResult(0, "登陆失败", null);
			return  result;
		}
		 
	
	}

	public int add(User user) {
		user.setStatus(1);
		user.setPassword("123456");
		return userMapper.insert(user);
	}

	public PageInfo<User> listByPage(Integer currentPage,String usercode) {
		// 1 定义当前页  和 一页显示的行数 
		  PageHelper.startPage(currentPage, 20);  
		 
		
		  UserExample example = new UserExample();
		 Criteria createCriteria = example.createCriteria();
		 if(usercode!=null && !"".equals(usercode)) {
			 createCriteria.andUsercodeEqualTo(usercode);
		 }
		 
	 
		 // 2  调用查询语句  
		List<User> list =   userMapper.selectAllUser(example);
		
		PageInfo<User> pageInfo = new PageInfo<User>(list);
		return pageInfo;
	}

	public int delete(Integer uid) {
		 
		return userMapper.deleteByPrimaryKey(uid);
	}

	public boolean updatePwd(Integer id, String newpassword) {
		User user = new User();
		user.setId(id);
		user.setPassword(newpassword);
		int count = userMapper.updatePwd(user);
		if(count>0) {
			return true;
		}
		return false;
	}

}
